#include "friendslist.h"

#include "common/friend.h"
#include "friendsitem.h"

#include <QWidget>

namespace Ui {

FriendsList::FriendsList(QWidget* _parent) : QTreeWidget(_parent) { 
	on = new QTreeWidgetItem();
	on->setText(0,"Online");
	addTopLevelItem(on);

	off = new QTreeWidgetItem();
	off->setText(0,"Offline");
	addTopLevelItem(off);

	setColumnCount(1);
	setHeaderLabel("Friends");
	connect(this,SIGNAL(itemDoubleClicked(QTreeWidgetItem *, int)),this,SLOT(friendDoubleClicked(QTreeWidgetItem *, int)));
}

FriendsList::~FriendsList() { }

int FriendsList::getId(QString _login) {
	QMap<int, FriendsItem*>::const_iterator i = friends.constBegin();
	while (i != friends.constEnd()) {
		FriendsItem* item = i.value();
		Friend* _friend = item->getFriend();
		if(_friend->getLogin() == _login)
			return _friend->getId();
		++i;
	}
	return 0;
}

void FriendsList::removeFriend(int friendId) {
	delete friends.take(friendId);
}

Friend *FriendsList::getFriend(int friendId) {
	return friends[friendId]->getFriend();
}

void FriendsList::loadFriends(QList<Friend*> _friends) {
	for(int i = 0; i < _friends.size(); i++) {
		addFriend(_friends[i]);
	}
	on->setExpanded(true);
	on->sortChildren(0,Qt::AscendingOrder);
	off->setExpanded(true);
	off->sortChildren(0,Qt::AscendingOrder);
}

void FriendsList::updateFriend(Friend* _friend) {
	FriendsItem* item = friends[_friend->getId()];
	if(item != 0) {
		item->setFriendInfo(_friend);
		item->setIcon(0,getStatusIcon(_friend->getStatus()));
		item->parent()->removeChild(item);
		if(_friend->getStatus()==Offline){
			off->addChild(item);
			off->sortChildren(0,Qt::AscendingOrder);
		}
		else {
			on->addChild(item);
			on->sortChildren(0,Qt::AscendingOrder);
		}
	}
}

void FriendsList::addFriend(Friend* _friend) {
	FriendsItem* item = new FriendsItem(_friend);
	friends[_friend->getId()] = item;
	item->setIcon(0,getStatusIcon(_friend->getStatus()));
	if(_friend->getStatus()==Offline) {
		off->addChild(item);
	}
	else {
		on->addChild(item);
	}
}

void FriendsList::friendDoubleClicked(QTreeWidgetItem *item,int) {
	if(indexOfTopLevelItem(item)==-1) {
		Friend * friend_ = (static_cast<FriendsItem *>(item))->getFriend();
		if(friend_->getStatus()!=Offline)
			emit startChat(friend_->getId());
	}
}

QIcon FriendsList::getStatusIcon(Status _status) const {
	switch(_status) {
		case Online:
			return QIcon("data/img/online.png");
		case Away:
			return QIcon("data/img/away.png");
		case Inactivity:
			return QIcon("data/img/inactivity.png");
		default:
			return QIcon("data/img/offline.png");
	}
}
	}

